package com.task.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.task.bean.Task;
import com.task.bean.TaskExec;
import com.task.service.ITaskExecService;
import com.task.vo.ResultVo;
import com.task.vo.TaskExecQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liuzhe
 * @since 2021-04-10
 */
@RestController
@RequestMapping("/task-exec")
@Slf4j
public class TaskExecController {

    @Autowired
    private ITaskExecService taskExecService;

    // 文件上传目录
    @Value("${upload.dir}")
    private String uploadDirectory;

    // 图片访问路径前缀
    @Value("${upload.path}")
    private String path;

    @PostMapping("/list")
    public ResultVo list(@RequestBody TaskExecQuery execQuery,@RequestParam("teaId") int teaId) throws ParseException {
        return ResultVo.success(taskExecService.queryTaskExecListByStuId(execQuery,teaId));
    }
//    @PostMapping("/query")
//    public ResultVo query(int teaId, @RequestBody TaskExec taskExec) {
//        return ResultVo.success(taskExecService.queryTaskExecAndStu(teaId, taskExec));
//    }

    @GetMapping("/query")
    public ResultVo query(int stuId) {
        return ResultVo.success(taskExecService.queryTaskExecAndTaskByStuId(stuId));
    }

    @PostMapping("/add")
    public ResultVo add(@RequestBody TaskExec taskExec) {
        taskExec.setCreateTime(new Date());
        return ResultVo.success(taskExecService.save(taskExec));
    }
    @PostMapping("/upload")
    public ResultVo upload(MultipartFile file){
        String originFileName = file.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(originFileName);
        String uuid = UUID.randomUUID().toString().replace("-","");
        String newFileName = uuid + "." + suffix;
        File uploadDir = new File(this.uploadDirectory);
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        // 创建目标文件
        File newFile = new File(this.uploadDirectory,newFileName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String picPath = path + newFileName;
        // 打印图片地址
        log.info("图片地址 - {}",picPath);
        return ResultVo.success(picPath);
    }

//    @GetMapping("/query")
//    public ResultVo query(int id) {
//        return ResultVo.success(taskExecService.getById(id));
//    }
}

